using CGF;
using LitJson;
using UnityEngine;

public class PushMsgClient
{
    private static WebSocketClient ws;
    private PushMsgClient() { }
    public static PushMsgClient Instance = new PushMsgClient();

    public async void Start()
    {
        if (ws != null)
        {
            Debug.LogError($"[PushMsgClient] 连接已存在]");
            return;
        }
        ws = new WebSocketClient();
        ws.onMessage = OnReceiveMsg;
        Debug.Log($"[PushMsgClient] 开始连接");
        bool connSuccess = await ws.Connect(Config.Get.SellPushWsUrl);
        if (connSuccess)
        {
            //1：链接
            SendMsg(1, "connect", null);
        }
    }

    private void OnReceiveMsg(string msg, byte[] _data)
    {
        //{"id":1,"connect":{"client":"14f93456-7166-4d10-adc5-3de4c164baa6","version":"6.3.1 OSS","ping":25,"pong":true}}
        Debug.Log($"[PushMsgClient] OnReceiveMsg: {msg}");
        if (msg == "{}")
        {
            ws.Send("{}");
            return;
        }
        JsonData json = JsonMapper.ToObject(msg);
        if (json.Contains("id"))
        {
            int msgId = (int)json["id"];
            switch (msgId)
            {
                case 1:
                    //2：订阅
                    JsonData data = new JsonData();
                    data["channel"] = $"user:{UserInfo.UserId}";
                    SendMsg(2, "subscribe", data);
                    break;
            }
        }
        else if (json.Contains("push"))
        {
            JsonData push = json["push"];
            string channel = push["channel"].ToString();
            if (channel.Contains(UserInfo.UserId))
            {
                //刷新钱包
                UserInfo.RefreshWallet();
                if (TabMeCtrl.AutoPushMsg)
                {
                    JsonData data = push["pub"]["data"];
                    string deviceId = data["bot_id"].ToString();
                    string amount = StringHelper.Format2Decimal((int)data["reward"] * 0.01f);
                    RootComponent.instance.GetComponent<PopupSucSold>()?.Destroy();
                    PopupSucSold.Open(deviceId, amount);
                }
            }
        }
    }

    public void SendMsg(int id, string cmd, JsonData data)
    {
        JsonData json = new JsonData();
        json["id"] = id;
        json[cmd] = data != null ? data : new JsonData();
        string msg = json.ToJson();
        Debug.Log($"[PushMsgClient] SendMsg: {msg}");
        ws.Send(msg);
    }

    public void Stop()
    {
        if (ws != null)
        {
            ws.Disconnect();
            ws = null;
        }
    }
}
